<!--
树形数据回显
@author luguoxiang
@Date: 2024/05/13 08:55
开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <slot :items="items" :labels="labels">{{ labels.join(separator) }}</slot>
</template>

<script lang="ts" setup>
import {computed} from "vue";

const props = defineProps<{
  options: any[];
  value: any;
  separator?: string;
  childrenKey?: string;
  valueKey?: string;
  labelKey?: string;
}>()

const separator = props.separator || ' / ';
const childrenKey = props.childrenKey || 'children';
const valueKey = props.valueKey || 'value';
const labelKey = props.labelKey || 'label';

function getLink(options: any[], id: any) {
  const call: Function = (list: any[]) => {
    for (const x of list) {
      if (x[valueKey] === id) {
        return [x]
      }
      const children = x[childrenKey]
      if (children) {
        const res: any[] | undefined = call(children)
        if (Array.isArray(res)) {
          res.unshift(x)
          return res;
        }
      }
    }
  }
  return call(options) ?? []
}

const items = computed(() => {
  return getLink(props.options, props.value)
})

const labels = computed(() => {
  return items.value.map((x: any) => x[labelKey])
})
</script>
<script lang="ts">
export default {
  name: 'LgTreeLabel'
}
</script>
